const {Sequelize, DataTypes} = require('sequelize');
const sequelize = new Sequelize({
    dialect: 'sqlite',
    storage: './data.sqlite'
});

(async () => {
    try {
        await sequelize.authenticate();
        console.log('Connection has been established successfully.');
    } catch (error) {
        console.error('Unable to connect to the database:', error);
    }
})()

const Air = sequelize.define('air', {
    id: {
        type: DataTypes.INTEGER,
        autoIncrement: true,
        primaryKey: true,
        unique: true
    },
    tvoc: {
        type: DataTypes.INTEGER
    },
    co2: {
        type: DataTypes.INTEGER
    },
    temp: {
        type: DataTypes.FLOAT
    },
    humi: {
        type: DataTypes.FLOAT
    },
    fanStatus: {
        type: DataTypes.BOOLEAN
    }
})


const express = require("express");
const app = express();
const bodyParser = require("body-parser");
app.use(bodyParser.json());

app.get('/init', async (req, res) => {
    await sequelize.sync({force: true});
    res.send("service is ready!")
})

app.post("/test", async (req, res) => {
    const {tvoc, co2, temp, humi} = req.body
    await Air.create({
        tvoc,
        co2,
        temp,
        humi,
        fanStatus: false
    })
    res.send('OK')

});
app.listen(3000, () => {

    console.log("service is running in port 3000");
});
